package com.wb.mas.ui.auth;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wb.mas.BR;
import com.wb.mas.BuildConfig;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.app.Constants;
import com.wb.mas.databinding.ActAuthIdBinding;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.ui.view.datepicker.CustomDatePicker;
import com.wb.mas.ui.view.datepicker.DateFormatUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;

import androidx.lifecycle.ViewModelProviders;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ImageUtils;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthIdAc extends BaseActivity<ActAuthIdBinding, AuthIdViewModel> {

    public static final int TAKE_PHOTO_REQUEST_CODE1 = 101;
    public static final int TAKE_PHOTO_REQUEST_CODE2 = 102;
    private static final String FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID+".fileprovider";
    private static final String TAG = AuthIdAc.class.getSimpleName();
    private Uri mImageUri;
    private CustomDatePicker mDatePicker;
    private File imageFile;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_auth_id;
    }

    @Override
    public int initVariableId() {
        return BR.viewmodel;
    }


    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .barColor(me.goldze.mvvmhabit.R.color.white)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .navigationBarColor(me.goldze.mvvmhabit.R.color.white)
                .init();  //必须调用方可沉浸式
    }

    @Override
    public AuthIdViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(AuthIdViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
//        setSupportActionBar(binding.titleBar.toolbar);
        viewModel.initToolBar();
        initDatePicker();

    }


    private void initDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("1980-01-01", false);
        long endTimestamp = System.currentTimeMillis();


        viewModel.idCardBirthday.set("2009-05-01");
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                binding.etInputBirthday.setText(DateFormatUtils.long2Str(timestamp, false));
            }
        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(false);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.takePhoto1Event.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                requestCameraPermissions(TAKE_PHOTO_REQUEST_CODE1);

            }
        });


        viewModel.uc.takePhoto2Event.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {

                requestCameraPermissions(TAKE_PHOTO_REQUEST_CODE2);
            }
        });
        viewModel.uc.birthdayClickEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                String showTime = binding.etInputBirthday.getText().toString();

                mDatePicker.show(TextUtils.isEmpty(showTime) ? "2009-05-01" : showTime);

            }
        });

    }

    public void doTakePhoto(int requestCode) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            //创建用来保存照片的文件
            imageFile = createImageFile();
            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*7.0以上要通过FileProvider将File转化为Uri*/
                    mImageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
                } else {
                    /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
                    mImageUri = Uri.fromFile(imageFile);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(takePhotoIntent, requestCode);//打开相机
            }
        }
    }


    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
//        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
//            imageFile = new File(storageDir,imageFileName+".jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }


    /**
     * 请求相机权限
     */
    private void requestCameraPermissions(final int takePhotoRequestCode) {
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(AuthIdAc.this);
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            doTakePhoto(takePhotoRequestCode);
                        } else {
                            ToastUtils.showShort("权限被拒绝");
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if ((requestCode == TAKE_PHOTO_REQUEST_CODE1 || requestCode == TAKE_PHOTO_REQUEST_CODE2) && resultCode == RESULT_OK) {
            try {
                /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));


                if (requestCode == TAKE_PHOTO_REQUEST_CODE1) {
                    doUploadImg(mImageUri, imageFile, Constants.FILE_TYPE_OF_1);

                } else if (requestCode == TAKE_PHOTO_REQUEST_CODE2) {
                    doUploadImg(mImageUri, imageFile, Constants.FILE_TYPE_OF_2);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private void doUploadImg(final Uri mImageUri, final File imageFile, final String fileType) {
        if (mImageUri == null) {
            KLog.e(TAG, "mImageUri is null");
            return;
        }
        KLog.e(TAG, "mImageUri's path is:" + mImageUri.getPath());
        showDialog();


        ImageUtils.compressWithRx(imageFile.getAbsolutePath(), new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                dismissDialog();
                if (o instanceof File) {

                    File photoFile = (File) o;
                    if (Constants.FILE_TYPE_OF_1.equals(fileType)) {
                        SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean identityImagesBean = new SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean();
                        identityImagesBean.setLocalPath(photoFile.getAbsolutePath());
                        identityImagesBean.setFileType(Integer.parseInt(Constants.FILE_TYPE_OF_1));
                        viewModel.idCardPositiveBean.set(identityImagesBean);

                    } else if (Constants.FILE_TYPE_OF_2.equals(fileType)) {
                        SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean identityImagesBean = new SubmitedAuthResponse.DataBean.IdentityBean.IdentityImagesBean();
                        identityImagesBean.setLocalPath(photoFile.getAbsolutePath());
                        identityImagesBean.setFileType(Integer.parseInt(Constants.FILE_TYPE_OF_2));
                        viewModel.idCardNegativeBean.set(identityImagesBean);
                    }
                    viewModel.doUploadImg(mImageUri, photoFile, fileType);
                }

            }
        });
    }


}
